#include<iostream>
#include<semaphore.h>
#include<pthread.h>
#include<unistd.h>
using namespace std;

class Sem{
  private:
    sem_t sem;
  public:
    Sem(int _val=1)
    {
      sem_init(&sem,0,_val);
    }
    
    void P()
    {
      sem_wait(&sem);
    }

    void V()
    {
      sem_post(&sem);
    }
    ~Sem()
    {
      sem_destroy(&sem);
    }
};

Sem sem(1);
int tickets=1000;
void* Gettickets(void* arg)
{
  while(1)
  {
    sem.P();
    if(tickets>0)
    {
      usleep(10000);
   //   cout<<(char*)arg<<" get ticket: "<<tickets--<<endl;
      printf("%s get ticket: %d\n",(char*)arg,tickets--);
      sem.V();
    }

    else 
    {
      sem.V();
      break;
    }
  }
//  cout<<(char*)arg<<" quit"<<endl;
    printf("%s quit!!\n",(char*)arg);
  pthread_exit((void*)0);
}

int main()
{
 pthread_t tid1,tid2,tid3;
 pthread_create(&tid1,nullptr,Gettickets,(void*)"thread 1");
 pthread_create(&tid2,nullptr,Gettickets,(void*)"thread 2");
 pthread_create(&tid3,nullptr,Gettickets,(void*)"thread 3");
 

 pthread_join(tid1,nullptr);
 pthread_join(tid2,nullptr);
 pthread_join(tid3,nullptr);
  return 0;
}


